package com.jl.smartcard.ui;

import java.io.File;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.swt.graphics.Image;
import org.osgi.framework.Bundle;

public class ImageShop {
	private static ImageRegistry register = new ImageRegistry();
	private static Set<String> keys = new HashSet<String>();
	static {
		initial();
	}

	public static ImageDescriptor getDescriptor(String key) {
		ImageDescriptor image = register.getDescriptor(key);
		if (image == null) {
			image = ImageDescriptor.getMissingImageDescriptor();
		}
		return image;
	}

	public static Image get(String key) {
		Image image = register.get(key);
		if (image == null) {
			image = ImageDescriptor.getMissingImageDescriptor().createImage();
		}
		return image;
	}

	public static String[] getImageKey() {
		return keys.toArray(new String[keys.size()]);
	}

	private static void initial() {
		Bundle bundle = Platform.getBundle(SmartCardUI.ID_APPLICATION);
		URL url = bundle.getEntry("icons");
		try {
			url = FileLocator.toFileURL(url);
		} catch (Exception e) {
			// Application.log("get root path", e);
		}
		File file = new File(url.getPath());
		File[] images = file.listFiles();
		for (int i = 0; i < images.length; i++) {
			File f = images[i];
			if (!f.isFile()) {
				continue;
			}
			String name = f.getName();
			if (name.endsWith(".gif") || name.endsWith(".png") || name.endsWith(".ico")) {
				String key = name.substring(0, name.indexOf('.'));
				URL fullPathString = bundle.getEntry("icons/" + name);
				ImageDescriptor des = ImageDescriptor.createFromURL(fullPathString);
				register.put(key, des);
				keys.add(key);
			}else{
				continue;
			}
			
		}
	}
}